import { useState } from 'react'
import { useAtom } from 'jotai'
import { useTranslation } from 'react-i18next'
import { Settings, Chat, Assistant, DataStorePlatform } from '@/types'
import { chatsAtom, assistantListAtom, settingsAtom, syncConfigAtom, activeSyncTypeAtom } from '@/atoms'
import PasswordTextField from '@/components/Base/PasswordTextField'
import {
  Box,
  FormGroup, FormControlLabel, FormControl, FormLabel,
  Checkbox, Button, TextField, InputLabel, Select, MenuItem,
} from '@mui/material'
import useSyncData from '@/hooks/useSyncData'

enum ExportDataItem {
  Setting = 'setting',
  Chat = 'chats',
  Assistant = 'assistants',
}

export default function DataSyncSettingTab({ settingsEdit }: {
  settingsEdit: Settings
  setSettingsEdit: (settings: Settings) => void
}) {
  const { t } = useTranslation()
  const { uploadData, downloadData } = useSyncData()

  const [chatsData, setChatsData] = useAtom(chatsAtom)
  const [assistantsData, setAssistantsData] = useAtom(assistantListAtom)
  const [, setSettingsData] = useAtom(settingsAtom)
  const [syncConfig, setSyncConfig] = useAtom(syncConfigAtom)
  const [activeSyncType, setActiveSyncType] = useAtom(activeSyncTypeAtom)

  const [uploadResult, setUploadResult] = useState(0) // 1成功,2失败
  const [downloadResult, setDownloadResult] = useState(0)

  const [exportItems, setExportItems] = useState<ExportDataItem[]>([
    ExportDataItem.Setting,
    ExportDataItem.Chat,
    ExportDataItem.Assistant,
  ])

  const updateHandle = (data: { url?: string, key?: string }) => {
    setSyncConfig((syncConfig) => {
      return {
        ...syncConfig,
        [activeSyncType]: {
          ...syncConfig[activeSyncType],
          ...data,
        },
      }
    })
  }

  const onExport = async () => {
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const data: any = {}
    const date = new Date()
    data['exported_items'] = exportItems
    data['exported_at'] = date.toISOString()

    if (exportItems.indexOf(ExportDataItem.Setting) >= 0)
      data['setting'] = { base: settingsEdit, sync: syncConfig }
    if (exportItems.indexOf(ExportDataItem.Chat) >= 0)
      data['chats'] = chatsData
    if (exportItems.indexOf(ExportDataItem.Assistant) >= 0)
      data['assistant'] = assistantsData

    const res = await uploadData(data)
    setUploadResult(res ? 1 : 2)
  }
  const onImport = async () => {
    const data = await downloadData() as { setting: Settings, chats: Chat[], assistant: Assistant[] }
    if (data) {
      if (exportItems.indexOf(ExportDataItem.Setting) >= 0 && data['setting'])
        setSettingsData(data['setting'])

      if (exportItems.indexOf(ExportDataItem.Chat) >= 0 && data['chats'])
        setChatsData(data['chats'])

      if (exportItems.indexOf(ExportDataItem.Assistant) >= 0 && data['assistant'])
        setAssistantsData(data['assistant'])

      setDownloadResult(1)
    }
  }
  return (
    <Box className="flex flex-col gap-2">
      <FormControl fullWidth>
        <InputLabel>{t('存储平台')}</InputLabel>
        <Select
          label={t('存储平台')}
          value={activeSyncType}
          className="w-full"
          onChange={e => setActiveSyncType(e.target.value as DataStorePlatform)}
        >
          {Object.values(DataStorePlatform).map(option => (
            <MenuItem key={option} value={option}>
              {option}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
      {
        activeSyncType === DataStorePlatform.JsonStorage && (
          <TextField
            margin="dense"
            label="CloudUrl"
            value={syncConfig[activeSyncType].url}
            placeholder="https://api.jsonstorage.net/v1/json/{userid}/{itemid}"
            onChange={(e) => {
              let value = e.target.value
              value = value.trim()
              if (value.length > 4 && !value.startsWith('http')) {
                value = 'https://' + value
              }
              updateHandle({ url: value })
            }}
          />
        )
      }
      <PasswordTextField
        label="APIKey"
        value={syncConfig[activeSyncType].key}
        placeholder="Api key for CloudUrl"
        onChange={val => updateHandle({ key: val })}
      />
      <Box>
        <FormControl>
          <FormLabel>Data type</FormLabel>
          <FormGroup row>
            {[
              { label: t('storage setting'), value: ExportDataItem.Setting },
              { label: t('storage chat'), value: ExportDataItem.Chat },
              { label: t('storage assistant'), value: ExportDataItem.Assistant },
            ].map(item => (
              <FormControlLabel
                label={item.label}
                key={item.label}
                control={(
                  <Checkbox
                    checked={exportItems.includes(item.value)}
                    onChange={(_, checked) => {
                      if (checked && !exportItems.includes(item.value)) {
                        setExportItems([...exportItems, item.value])
                      }
                      else if (!checked) {
                        setExportItems(exportItems.filter(v => v !== item.value))
                      }
                    }}
                  />
                )}
              />
            ))}
          </FormGroup>
        </FormControl>
        <Box className="flex gap-2">
          <Button variant="contained" color="primary" disabled={uploadResult > 0} onClick={onExport}>
            {uploadResult > 0 ? t('sync upload success') : t('sync upload') }
          </Button>
          <Button variant="contained" color="primary" disabled={downloadResult > 0} onClick={onImport}>
            {downloadResult > 0 ? t('sync download success') : t('sync download')}
          </Button>
        </Box>
      </Box>
    </Box>
  )
}
